package com.yk._01多线程买票程序;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class _02Lock锁卖票 {




    public static void main(String[] args) {

        TicketLock ticket_lock = new TicketLock(50);
        TicketLock ticketLock = new TicketLock();

        for(int i = 0;i < 3;i++) {
            new Thread(()->{
                for(int j = 0;j < 30;j++) {
                    ticket_lock.saleTicket();
                }
            }, i +"-线程").start();
        }

    }
}
/*资源类*/
@Data
@NoArgsConstructor
@AllArgsConstructor
class TicketLock {
    //资源类
    private int num;

    public final ReentrantLock reentrantLock = new ReentrantLock();

    public synchronized void saleTicket() {
        reentrantLock.lock();
        try {
            if (num > 0) {
                num--;
                System.out.println(Thread.currentThread().getName() + " 售票成功 剩余票数 == " + num);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            reentrantLock.unlock();
        }
    }
}
